// 手机号绑定页面逻辑
const userApi = require('../../api/userApi');
const app = getApp();

Page({
  data: {
    phone: '',
    code: '',
    validPhone: false,
    validForm: false,
    codeSent: false,
    countdown: 60,
    binding: false
  },

  onLoad: function (options) {
    // 页面初始化
  },

  // 手机号输入
  onPhoneInput: function (e) {
    const phone = e.detail.value;
    const validPhone = /^1[3-9]\d{9}$/.test(phone);
    
    this.setData({
      phone,
      validPhone,
      validForm: validPhone && this.data.code.length === 6
    });
  },

  // 验证码输入
  onCodeInput: function (e) {
    const code = e.detail.value;
    
    this.setData({
      code,
      validForm: this.data.validPhone && code.length === 6
    });
  },

  // 发送验证码
  sendCode: function () {
    if (this.data.codeSent || !this.data.validPhone) return;
    
    const phone = this.data.phone;
    
    userApi.sendCode(phone)
      .then(() => {
        this.setData({
          codeSent: true
        });
        
        // 开始倒计时
        this.startCountdown();
        
        wx.showToast({
          title: '验证码已发送',
          icon: 'success'
        });
      })
      .catch(err => {
        console.error('发送验证码失败', err);
      });
  },

  // 开始倒计时
  startCountdown: function () {
    let countdown = this.data.countdown;
    
    const timer = setInterval(() => {
      countdown--;
      
      if (countdown <= 0) {
        clearInterval(timer);
        this.setData({
          codeSent: false,
          countdown: 60
        });
      } else {
        this.setData({
          countdown
        });
      }
    }, 1000);
  },

  // 绑定手机号
  bindPhone: function () {
    if (!this.data.validForm || this.data.binding) return;
    
    const { phone, code } = this.data;
    
    this.setData({ binding: true });
    
    userApi.bindPhone(phone, code)
      .then(() => {
        // 绑定成功，获取用户信息
        return userApi.getUserInfo();
      })
      .then(userInfo => {
        // 保存用户信息
        app.globalData.userInfo = userInfo;
        app.globalData.points = userInfo.points || 0;
        
        wx.showToast({
          title: '绑定成功',
          icon: 'success'
        });
        
        // 跳转到首页
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/home/home'
          });
        }, 1500);
      })
      .catch(err => {
        console.error('绑定手机号失败', err);
      })
      .finally(() => {
        this.setData({ binding: false });
      });
  }
}); 